package device;

import java.util.ArrayList;

import memory.PCB;
import memory.PCBData;

public class DeviceManage {
	public static ArrayList<Device> devices = new ArrayList<Device>() {
		{
			add(new Device('A'));
			add(new Device('A'));
			add(new Device('B'));
			add(new Device('B'));
			add(new Device('B'));
			add(new Device('C'));
			add(new Device('C'));
			add(new Device('C'));
		}
	};
	private static DeviceManage deviceManage = null;

	private DeviceManage() {

	}

	public static DeviceManage createDeviceManage() {
		if (deviceManage == null)
			deviceManage = new DeviceManage();
		return deviceManage;
	}

	// 申请设备
	public static boolean callingDevice(char type, int pid, int machineTime) {
		for (Device device : devices)
			if (device.getPid() == -1 && device.getType() == type) {
				device.occupyDevice(machineTime, pid);
				System.out.println(pid+"  "+type +"设备调用成功");
				return true;
			}
		return false;
	}

	// 对所有占用设备进行倒计时
	public static void reduceAllTime() {
		for (Device device : devices)
			if (device.getPid() != -1)
				device.reduceMachineTime();
		// 如果为零，I/O中断标志为1
		for (Device device : devices)
			if (device.getMachineTime() == 0) {
				int index = PCB.searchAllPCB(device.getPid());
				if (index > -1)
					(PCBData.allPcbList.get(index)).setPsw_io(1);
			}

	}

	// 释放指定pid占用的设备并返回该设备是哪种设备
	public static char releaseDevice(int pid) {
		char type = '?';
		for (Device device : devices)
			if (pid == device.getPid()) {
				type = device.getType();
				device.releaseDevice();
			}
		return type;
	}

	// 判断是否有设备可以释放
	public static int canRelease() {
		int size = 0;
		for (Device device : devices) {
			if (device.getMachineTime() == 0) {
				size++;
			}
		}
		return size;
	}

	// 设备时间为零，获得占用该设备的pid
	public static int[] getTimeoutPid(int size) {
		if (size == 0) {
			return null;
		} else {
			int[] pids = new int[size];
			int index = 0;
			for (Device device : devices) {
				if (device.getMachineTime() == 0&&index<size) {
					pids[index] = device.getPid();
					index++;
				}
			}
			return pids;
		}
	}
}
